// packageStore/pages/perfect/perfect.js
import {perfect} from '../../../js/modules/store';
var app = getApp();
import BasePage from '../../../js/common/base-page'
import { util, forms, api } from '../../../js/util';
import {
  router
} from '../../../js/router';
import { isEmpty } from '../../../js/newUtil';
BasePage({
  pageKey:"perfect",
  validateLogin:false,
  /**
   * 页面的初始数据
   */
  data: {
    status:0,   //* 0 ：待完善（需跳转完善页）* 1：待审核（需跳转完善页）* 2：审核通过，待状态开启 （需跳转完善页）
    profileToken:'',
    fieldList:[],
    region: [],
    isSubmiting:false,
    stepIndex:1,      //当前步骤
    statusData:{},         //当前状态
    businessIdx:0,     //暂存经营范围索引
    businessTips:'',    //暂存经营范围值
    isIphoneX:app.globalData.isIphoneX,//适配手机
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //设置状态
    this.setData({
      status:options.profileStatus,
      profileToken:options.profileToken
    })
    this.getSetting();
  },
  /**
   * 获取资料设置项
   */
  getSetting:function(){
    let that = this;
    perfect.get_setting(this.data.profileToken,(res)=>{
      if (res.Success) {
        let stepIndex = res.Content.stepIndex;
        let formList = res.Content.data;
        if (stepIndex == 3) {
          router.redirect({
            path: "login",
            params: {
              token:res.Content.token
            }
          });
          return;
        }
        this.setData({
          stepIndex,
        })
        if (stepIndex == 2) {
          this.setData({
            statusData: formList[0]
          })
        }
        if(stepIndex == 1){
          let newlist = formList.filter((item)=>item.Preset!=2);
          newlist.map((item)=>{
            item.Value = item.Value||'';
            if(item.InputType=='select' && item.Value && item.Value != ''){
              let n = item.Items.findIndex(li=>li.checked=='1');
              item.pindex = n;
            }else if(item.InputType=='image' && item.Value && item.Value != ''){
              item.photos = item.Value.split(',').map((li)=> api.imgDomain+li);
            }else if (item.InputType == 'select_area' && item.Items && JSON.stringify(item.Items) != '{}') {
                item.region = Object.values(item.Items)
            }
          });
          this.setData({
            fieldList:newlist
          })
        }
      }
    })
  },
  /**
   * 选择地区
   */
  showPicker(e) {
    let that = this
    let picker = this.selectComponent('#pickerStreet')
    let idx = e.currentTarget.dataset.index
    let id = ''
    let {
      fieldList
    } = this.data
    try {
      let valueList = fieldList[idx].Value
      id = valueList[valueList.length - 1]
    } catch (error) {
      console.log('没有已有的id:', error)
    }
    picker.$$showComponent({
      Id: id,
      success(res) {
        console.log('选择的省市区街数据', res)
        let region = res.chineseValue || []
        let value = res.value || []
        region = region.filter((item) => {
          return item
        })
        value = value.filter((item) => {
          return item
        })
        let code = value.join('-')
        fieldList[idx].region = region
        fieldList[idx].Value = code
        that.setData({
          fieldList
        })
      }
    })
  },
  /**
   * 图片 
   */
  bindUploadPhoto(res){
    this.changeImg(res.detail.list,res.currentTarget.dataset.index);
  },
  onDelPhotoEvent(res){
    this.changeImg(res.detail.list,res.currentTarget.dataset.index);
  },
  changeImg(list,idx){
    let {fieldList} = this.data;
    fieldList[idx].Value = list;
    this.setData({
      fieldList
    })
  },
  /**
   * picker选择
   */
  bindPickerChange(e){
    let {fieldList} = this.data;
    let idx = e.currentTarget.dataset.index;
    fieldList[idx].pindex = e.detail.value;
    const items = fieldList[idx].Items;
    for(let i = 0; i<items.length;i++){
      items[i].checked = '0'
    }
    items[e.detail.value].checked = '1';
    fieldList[idx].Value = items[e.detail.value].value;
    this.setData({
      fieldList
    })
  },
  /**
   * 日期选择
   */
  bindEndDate(e){
    let {fieldList} = this.data;
    let idx = e.currentTarget.dataset.index;
    fieldList[idx].TimeValue = e.detail.value;
    this.setData({
      fieldList
    })
  },
  bindDateChange(e){
    let {fieldList} = this.data;
    let idx = e.currentTarget.dataset.index;
    fieldList[idx].Value = e.detail.value;
    this.setData({
      fieldList
    })
  },
  /**
   * 普通输入框/单选/复选
   */
  profileForm(e){
    let {fieldList} = this.data;
    let idx = e.currentTarget.dataset.index;
    let value = e.detail.value;
    fieldList[idx].Value = value;
    if(fieldList[idx].InputType=='checkbox'){    //复选
      const items = fieldList[idx].Items;
      const values = value;
      for (let i = 0, lenI = items.length; i < lenI; ++i) {
        items[i].checked = '0'
  
        for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
          if (items[i].value === values[j]) {
            items[i].checked = '1'
            break
          }
        }
      }
      fieldList[idx].Items = items;
    }else if(fieldList[idx].InputType=='radio'){    //单选
      const items = fieldList[idx].Items;
      for (let i = 0, len = items.length; i < len; ++i) {
        items[i].checked = items[i].value === value ? '1' : '0'
      }
      fieldList[idx].Items = items;
    }
    
    this.setData({
      fieldList
    })
  },
  /**
   * 验证
   */
  verify:function(callback){
    let {fieldList} = this.data;
    let allRight = true;
    console.log(fieldList,'=======');
    if(this.data.isSubmiting)return;
    for (let item of fieldList) {
      if (item.Required == 1) {
        if (item.InputType == 'image' && item.Value.length == 0) {
          util.tips('请上传' + item.Name);
          allRight = false
          break;
        }
        if (item.InputType == 'image' && item.Type == 2 && item.TimeValue == '') {
          util.tips('请选择' + item.Name + '到期时间');
          allRight = false
          break;
        }
        if (item.InputType == 'select_business' && item.Tips == '') {
          util.tips('请选择' + item.Name);
          allRight = false
          break;
        }
        if (item.Value == '' && item.InputType != 'image' && item.InputType != 'checkbox' && item.InputType != 'radio' && item.InputType != 'select' && item.InputType != 'select_business') {
          util.tips('请填写' + item.Name)
          allRight = false
          break
        }
        if (item.InputType == 'select_area') {
          let numberReg = /\d+/ // 校验是否已选择地区，选择后会有地区id
          if (isEmpty(item.Value) || !numberReg.test(item.Value)) {
            util.tips('请选择' + item.Name)
            allRight = false
            break
          }
        }
        allRight = this.verifyItem(item);  //验证正则输入内容
        if(allRight == false){
          break
        }
      }
      if(item.Value!=''){
        allRight = this.verifyItem(item);  //验证正则输入内容
        if(allRight == false){
          break
        }
      }
    }
    if (!allRight) return;
    if(callback&&typeof(callback) == "function"){
      callback();
    }
  },
  verifyItem:function(item){
    let allRight = true;
    if (item.Express == 'tel') {
      if (!forms.validate({value:item.Value,validate:'isnull|mobile'})) {
        util.tips('请输入正确的' + item.Name)
        allRight = false
      }
    }
    if (item.Express == 'email') {
      if (!forms.validate({value:item.Value,validate:'isnull|email'})) {
        util.tips('请输入正确的' + item.Name)
        allRight = false
      }
    }
    if (item.Express == 'idcard') {
      if (!forms.validate({value:item.Value,validate:'isnull|idcard'})) {
        util.tips('请输入正确的' + item.Name)
        allRight = false
      }
    }
    if (item.Express == 'chinese') {
      if (!forms.validate({value:item.Value,validate:'isnull|zh'})) {
        util.tips(item.Name + '只能输入中文')
        allRight = false
      }
    }
    if (item.Express == 'english') {
      if (!forms.validate({value:item.Value,validate:'isnull|en'})) {
        util.tips(item.Name + '只能输入字母')
        allRight = false
      }
    }
    if (item.Express == 'num') {
      if (!forms.validate({value:item.Value,validate:'isnull|n'})) {
        util.tips(item.Name + '只能输入数字')
        allRight = false
      }
    }
    if (item.Express == 'letter_number') {
      if (!forms.validate({value:item.Value,validate:'isnull|n_en'})) {
        util.tips(item.Name + '只能输入字母+数字')
        allRight = false
      }
    }
    if (item.Express == 'username') {
      if (!forms.validate({value:item.Value,validate:'isnull|zh_en_n'})) {
        util.tips(item.Name + '只能输入中文+字母+数字')
        allRight = false
      }
    }
    return allRight;
  },
  /**
   * 提交
   */
  submitPerfect:function(){
    this.verify(()=>{
      let {fieldList} = this.data;
      let Customize = '';
      for(let item of fieldList){
        if(item.InputType=='checkbox'||item.InputType=='radio'||item.InputType=='select'){
          let optList = [];
          item.Items.map((option) => {
              if (option.checked == '1') {
                  optList.push(option.value)
              }
          })
          Customize += `<item_${item.Id}>${optList.join(',')}</item_${item.Id}>`;
        }else if(item.InputType=='select_business'){
          Customize += `<item_${item.Id}>${item.Tips}</item_${item.Id}>`;
        }else{
          if(item.Type == 2 && item.InputType == 'image'){ 
            Customize += `<item_${item.Id}_time>${item.TimeValue}</item_${item.Id}_time>`;
          }
          Customize += `<item_${item.Id}>${item.Value}</item_${item.Id}>`; 
        }
      }
      let param = {
        Customize:Customize,
        profileToken:this.data.profileToken
      }
      console.log(param,'=======param');
      perfect.save(param,(res)=>{
        this.setData({
          isSubmiting : true
        })
        if(res.Success==true){
          this.getSetting();
        }else{
          util.tips(res.Message);
          this.setData({
            isSubmiting : false
          })
        }
      })
    });
  },
  /**
   * 重新提交
   */
  submitReapply:function(){
    perfect.reapply(this.data.profileToken,(res)=>{
      if(res.Success==true){
        this.getSetting();
      }else{
        util.tips(res.Message);
      }
    })
  },
  /**
   * 返回登录
   */
  backLogin:function(){
    router.redirect({
      path:'login'
    });
  },
  /**
   * 选择经营范围
   */
  showBusinessList:function(e){
    let {title,idx} = e.currentTarget.dataset;
    let {profileToken} = this.data;
    router.navigate({
      path:'business',
      params:{
        title:title,
        profileToken:profileToken,
        idx:idx
      }
    })
  },
  /**
   * 选择经营范围后
   */
  refreshPage:function(){
    let {fieldList,businessIdx,businessTips} = this.data;
    fieldList[businessIdx].Tips = businessTips;
    this.setData({
      fieldList
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})